package de.dhbw.karlsruhe.picsim.model.cpu.impl;

import de.dhbw.karlsruhe.picsim.model.actions.ActionFactory;
import de.dhbw.karlsruhe.picsim.model.cpu.PicInstructionFacade;
import de.dhbw.karlsruhe.picsim.model.cpu.ReadOnlyFile;
import de.dhbw.karlsruhe.picsim.model.memory.ReadOnlyFileMemory;
import de.dhbw.karlsruhe.picsim.model.memory.impl.FileAddressImpl;
import de.dhbw.karlsruhe.picsim.rs232.ProtocolLogic;
import de.dhbw.karlsruhe.picsim.util.Bits;
import de.dhbw.karlsruhe.picsim.util.impl.BitUtilities;
import org.jetbrains.annotations.NotNull;

import static de.dhbw.karlsruhe.picsim.util.impl.BitUtilities.asLeastSignificantBitFirst;

/**
 * Created by IntelliJ IDEA.
 * User: goesen
 * Date: Apr 18, 2010
 * Time: 7:28:54 PM
 */
public final class PicInstructionFacadeImpl implements PicInstructionFacade {
    private final ActionFactory actionFactory;
    private final ProtocolLogic rs2323;
    private final ReadOnlyFileMemory fileMemory;
    private final ReadOnlyFile wRegister;


    public PicInstructionFacadeImpl(final ReadOnlyFile wRegister, final ReadOnlyFileMemory fileMemory,
                                    final ActionFactory actionFactory, final ProtocolLogic rs2323) {
        this.wRegister = wRegister;
        this.fileMemory = fileMemory;
        this.actionFactory = actionFactory;
        this.rs2323 = rs2323;
    }

    @NotNull
    @Override
    public ReadOnlyFile getFor7BitAddress(@NotNull final Bits argument) {
        final int intArgument = BitUtilities.fromLeastSignificantBitFirst(argument);
        if (intArgument == 5 || intArgument == 6) {
            rs2323.sendMessageAndWait();
        }
        //wir füllen hier die 7 Bit Addresse des Befehls mit dem einen Bit aus dem RP0 Flag auf
        final boolean isBank2 = fileMemory.getFile(FileAddressImpl.statusAddress()).getData().isSet(5);

        final Bits highBit = asLeastSignificantBitFirst(isBank2 ? 1 : 0, 1);
        final Bits bits = BitUtilities.concat(argument, highBit);
        return fileMemory.getFile(new FileAddressImpl(bits));
    }

    @NotNull
    @Override
    public ReadOnlyFile getWRegister() {
        return wRegister;
    }

    @NotNull
    @Override
    public ActionFactory getActionFactory() {
        return actionFactory;
    }
}
